package com.zzxx.wechat.demo;

import com.zzxx.wechat.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

@Slf4j
public class HelloService {


    public static void main(String[] args) throws InterruptedException {
        String url = "https://arcteryx.com/us/en/shop/X000009141";
        // 查询Referer
        String protocolAndDomain = queryProtocolAndDomain(url);
        // 创建 CloseableHttpClient 实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建 HTTP GET 请求
            HttpGet request = new HttpGet(url);

            // 设置 User-Agent 和其他请求头（可选）
            //  request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
            request.setHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36");
            request.setHeader("Referer", protocolAndDomain);
            request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");

            // 发送请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                // 获取响应状态码
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("Response Status Code: " + statusCode);

                // 检查响应是否成功
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();

                    if (entity != null) {
                        // 获取 HTML 内容
                        String htmlStr = EntityUtils.toString(entity);
                        System.out.println("HTML Content Length: " + htmlStr.length());

                        // 使用 Jsoup 解析 HTML
                        Document document = Jsoup.parse(htmlStr);
                        Elements element = document.select("#__NEXT_DATA__");
                        String html = element.html();
                        if (StringUtils.isEmpty(html)) {
                            log.error("解析URL返回为空,链接:{}", url);
                            throw new BusinessException("解析URL返回为空,请确认输入链接正确");
                        }
                        log.info("解析URL返回JSON:{}", html);

                        System.out.println("Page Title: " + document.title());
                    }
                } else {
                    System.err.println("Failed to fetch the page. Status code: " + statusCode);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        Thread.sleep(5000);
    }


    private static String queryProtocolAndDomain(String url) {
        try {
            URL arcteryxUrl = new URL(url);
            return arcteryxUrl.getProtocol() + "://" + arcteryxUrl.getHost() + "/";
        } catch (MalformedURLException e) {
            throw new BusinessException("链接输入有误，请重新输入");
        }
    }
}
